/**
 * Copyright (C), 2020, JieYi Software System Co., Ltd.
 * All rights reserved.
 * FileName:       TableService.java
 *
 * @Description:
 * @author: feiwe
 * Modification History:
 * Date         Author        Version        Discription
 * -------------------------------------------------------
 * 2020/11/17      feiwe                         add
 */


package com.fengwei.service;

import com.fengwei.bean.Page;
import com.fengwei.executor.AbstractDbExecutor;
import com.fengwei.executor.MysqlExecutor;
import com.fengwei.form.MdmsDatabase;
import com.fengwei.form.MdmsUser;
import com.fengwei.requestdata.TableDdlData;
import com.fengwei.requestdata.TablePagingListData;
import com.fengwei.util.ExecutorConsts;
import com.fengwei.util.GsonUtil;
import com.fengwei.util.PltResult;
import com.fengwei.util.SpringContextUtil;
import com.fengwei.util.VerifyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TableService {
    private final static Logger logger = LoggerFactory.getLogger(TableService.class);

    public Map<String, Object> pagingList(TablePagingListData tablePagingListData, HttpServletRequest request) throws Exception {
        Map<String, Object> returnData = new HashMap<>();
        HttpSession session = request.getSession();
        MdmsDatabase mdmsDatabase = (MdmsDatabase) session.getAttribute("currentDatabaseId");
        if(null == mdmsDatabase){
            throw new VerifyException(PltResult.RESULT_CF303);
        }

        String sql = "select * from "+tablePagingListData.getTable()+"";

        AbstractDbExecutor abstractDbExecutor = (AbstractDbExecutor) SpringContextUtil.getBean(mdmsDatabase.getDatabaseType() + "Executor");
        String url = abstractDbExecutor.genUrl(mdmsDatabase.getDatabaseType(),mdmsDatabase.getDatabaseHost(),mdmsDatabase.getDatabasePort(),
                mdmsDatabase.getDatabaseDbname());
        Connection connection = null;
        try{
            connection = abstractDbExecutor.getConnection(mdmsDatabase.getId()+"",url,mdmsDatabase.getDatabaseUser(),mdmsDatabase.getDatabasePassword());
            List resultList = new ArrayList();
            StringBuffer sbRunLog = new StringBuffer();
            Page page = new Page();
            page.setPageNo(tablePagingListData.getPage());
            page.setPageSize(tablePagingListData.getLimit());
            Page<Map<String, Object>> pageResult = abstractDbExecutor.executeSelectSql(page,connection,sql);
            logger.debug("pageResult:"+ GsonUtil.toJson(pageResult,false));

            resultList.add(pageResult);


            returnData.put("resultList",resultList);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            // 数据库不存在
            throw new VerifyException(PltResult.RESULT_CF304);
        }finally {
            abstractDbExecutor.closeConnection(connection);
        }

        return returnData;

    }

    public Map<String, Object> ddl(TableDdlData tableDdlData, HttpServletRequest request, MdmsUser mdmsUser) throws Exception {
        Map<String, Object> returnData = new HashMap<>();
        HttpSession session = request.getSession();
        MdmsDatabase mdmsDatabase = (MdmsDatabase) session.getAttribute("currentDatabaseId");
        if(null == mdmsDatabase){
            throw new VerifyException(PltResult.RESULT_CF303);
        }

        AbstractDbExecutor abstractDbExecutor = (AbstractDbExecutor) SpringContextUtil.getBean(mdmsDatabase.getDatabaseType() + "Executor");
        String url = abstractDbExecutor.genUrl(mdmsDatabase.getDatabaseType(),mdmsDatabase.getDatabaseHost(),mdmsDatabase.getDatabasePort(),
                mdmsDatabase.getDatabaseDbname());
        Connection connection = null;
        try{
            connection = abstractDbExecutor.getConnection(mdmsDatabase.getId()+"",url,mdmsDatabase.getDatabaseUser(),mdmsDatabase.getDatabasePassword());

            String ddl = abstractDbExecutor.ddl(connection,tableDdlData.getTable(),mdmsDatabase.getDatabaseUser());
            returnData.put("ddl",ddl);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            // 数据库不存在
            throw new VerifyException(PltResult.RESULT_CF304);
        }finally {
            abstractDbExecutor.closeConnection(connection);
        }

        return returnData;
    }
}
